package com.project_doctor.controller;




import com.project_doctor.utils.MinioUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.UUID;
import java.util.Map;

@Slf4j
@RestController
@CrossOrigin(origins = "http://localhost:9090") // 允许前端跨域访问
@RequestMapping("/api")
public class MinioController {
    @Autowired
    MinioUtils minioUtils;
    @Value("${spring.minio.url}")
    String url;
    @Value("${spring.minio.bucket-name}")
    String bucketName;

    @PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
    public ResponseEntity<?> upload(@RequestParam("file") MultipartFile file) {
        try {
            log.info("接收到文件上传请求，文件名: {}", file.getOriginalFilename());
            log.info("文件大小: {} bytes", file.getSize());

            String name = UUID.randomUUID().toString();
            String fileName = name.substring(0,5) + "_" + file.getOriginalFilename();

            minioUtils.upload(file, fileName);
            log.info("文件上传成功: {}", fileName);

            String path = url + "/" + bucketName + "/" + fileName;
            Map<String, Object> response = new HashMap<>();
            response.put("code", 200);
            response.put("message", "上传成功");
            response.put("data", path);

            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("code", 500);
            errorResponse.put("message", "上传失败: " + e.getMessage());

            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body(errorResponse);
        }

//        String name=UUID.randomUUID().toString();
//        String fileName = name.substring(0,5);
//        minioUtils.upload(file,fileName);
//        log.info("文件上传成功: {}", fileName);
//        //http://localhost:9000/桶名/文件名
//        String path=url+"/"+bucketName+"/"+fileName;
//        return ResponseEntity.ok(path);
    }

}
